package com.example.androidproject.my.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;

import com.example.androidproject.R;
import com.example.androidproject.base.BaseFragment;
import com.example.androidproject.my.bean.LoginBean;
import com.example.androidproject.retrofit.RetrofitService;
import com.example.androidproject.utils.GlobalVariable;
import com.example.androidproject.utils.RequestConstant;

import java.sql.Time;
import java.util.Date;
import java.util.Timer;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyFragment extends BaseFragment implements View.OnClickListener, View.OnFocusChangeListener {
    private static final String TAG = "GGSTUDY";
    private SharedPreferences sp;
    private CardView rl_innerLoginPage;
    private Button btn_to_login, btn_close, btn_login, btn_register, btn_certain, btn_cancel, btn_close1, btn_register1;
    private TextView user, btn_watch, btn_read, btn_collect, btn_backLogin;
    private EditText tv_account, tv_password, tv_new_account, tv_new_password;
    private RelativeLayout rl_loginPage, unLogin_page, Login_page, rl_isBackLogin, rl_registerPage;
    private ImageView iv_user;
    private boolean is_rl_innerClick = false;
    private CheckBox check_remember;
    private Retrofit retrofit;
    private SharedPreferences.Editor edit;
    private boolean rememberPwd;

    @Override
    public View initView() {
        Log.e(TAG, "我的视图被初始化了");
        View view = View.inflate(mContext, R.layout.fragment_my, null);
        unLogin_page = view.findViewById(R.id.unLogin_page);
        Login_page = view.findViewById(R.id.Login_page);
        btn_close = view.findViewById(R.id.btn_close);
        btn_login = view.findViewById(R.id.btn_login);
        user = view.findViewById(R.id.user);
        btn_to_login = view.findViewById(R.id.btn_to_login);
        btn_register = view.findViewById(R.id.btn_register);
        btn_watch = view.findViewById(R.id.btn_watch);
        btn_read = view.findViewById(R.id.btn_read);
        btn_collect = view.findViewById(R.id.btn_collect);
        btn_backLogin = view.findViewById(R.id.btn_backLogin);
        tv_account = view.findViewById(R.id.tv_account);
        tv_password = view.findViewById(R.id.tv_password);
        rl_loginPage = view.findViewById(R.id.rl_loginPage);
        iv_user = view.findViewById(R.id.iv_user);
        rl_innerLoginPage = view.findViewById(R.id.rl_innerLoginPage);
        check_remember = view.findViewById(R.id.check_remember);
        rl_isBackLogin = view.findViewById(R.id.rl_isBackLogin);
        btn_certain = view.findViewById(R.id.btn_certain);
        btn_cancel = view.findViewById(R.id.btn_cancel);
        rl_registerPage = view.findViewById(R.id.rl_registerPage);
        btn_close1 = view.findViewById(R.id.btn_close1);
        btn_register1 = view.findViewById(R.id.btn_register1);
        tv_new_account = view.findViewById(R.id.tv_new_account);
        tv_new_password = view.findViewById(R.id.tv_new_password);

        sp = getActivity().getSharedPreferences("config", Context.MODE_PRIVATE);
        edit = sp.edit();
        retrofit = new Retrofit.Builder().baseUrl(RequestConstant.BASE).addConverterFactory(GsonConverterFactory.create()).build();
        initPage();
        return view;
    }

    @Override
    public void initData() {
        super.initData();
        Log.e(TAG, "我的数据被初始化了");

        // 回显数据
        rememberPwd = sp.getBoolean("rememberPwd", false);

        if (rememberPwd) {
            String username = sp.getString("username", "");
            String password = sp.getString("password", "");
            tv_account.setText(username);
            tv_password.setText(password);
            check_remember.setChecked(true);
        }
    }

    private void initPage() {
        rl_innerLoginPage.bringToFront();
        if (!GlobalVariable.token.isEmpty()) {
            Login_page.setVisibility(View.VISIBLE);
            unLogin_page.setVisibility(View.GONE);
            user.setText(sp.getString("username", ""));
        } else {
            unLogin_page.setVisibility(View.VISIBLE);
            Login_page.setVisibility(View.GONE);
        }
        eventListener();
    }

    private void eventListener() {
        // 点击事件
        btn_to_login.setOnClickListener(this);
        rl_loginPage.setOnClickListener(this);
        btn_close.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_register.setOnClickListener(this);
        rl_innerLoginPage.setOnClickListener(this);
        btn_backLogin.setOnClickListener(this);
        btn_certain.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        btn_watch.setOnClickListener(this);
        btn_read.setOnClickListener(this);
        btn_collect.setOnClickListener(this);
        btn_close1.setOnClickListener(this);
        btn_register1.setOnClickListener(this);
        // 获取焦点
        tv_account.setOnFocusChangeListener(this);
        tv_password.setOnFocusChangeListener(this);

    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_to_login:
            case R.id.rl_innerLoginPage:
                if (!rememberPwd) {
                    tv_account.setText("");
                    tv_password.setText("");
                    check_remember.setChecked(false);
                } else {
                    String username = sp.getString("username", "");
                    String password = sp.getString("password", "");
                    tv_account.setText(username);
                    tv_password.setText(password);
                    check_remember.setChecked(true);
                }
                rl_loginPage.setVisibility(View.VISIBLE);
                break;
            case R.id.rl_loginPage:
            case R.id.btn_close:
                rl_loginPage.setVisibility(View.GONE);
                break;
            case R.id.btn_login:
                String userName = String.valueOf(tv_account.getText()).trim();
                String password = String.valueOf(tv_password.getText()).trim();
                if (!userName.equals("") && !password.equals("")) {
                    RetrofitService retrofitService = retrofit.create(RetrofitService.class);
                    Call<LoginBean> loginBeanCall = retrofitService.login(userName, password);
                    loginBeanCall.enqueue(new Callback<LoginBean>() {
                        @Override
                        public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                            if (response.isSuccessful()) {
                                LoginBean body = response.body();
                                assert body != null;
                                if (body.getStatus() != 0) {
                                    ShowTipsHandler.sendMessage(new Message());
                                    edit.putString("username", "");
                                    edit.putString("password", "");
                                    edit.putBoolean("rememberPwd", false);
                                    edit.apply();
                                } else {
                                    // token 有效期 10 小时
                                    edit.putString("token", body.getToken());
                                    edit.putLong("recordTime", System.currentTimeMillis());
                                    edit.apply();
                                    GlobalVariable.token = body.getToken();
                                    rl_loginPage.setVisibility(View.GONE);
                                    unLogin_page.setVisibility(View.GONE);
                                    Login_page.setVisibility(View.VISIBLE);
                                    user.setText(userName);
                                    Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<LoginBean> call, Throwable t) {

                        }
                    });
                    if (check_remember.isChecked()) {
                        edit.putBoolean("rememberPwd", true);
                        edit.putString("username", userName);
                        edit.putString("password", password);
                        edit.apply();
                    } else {
                        edit.putString("username", "");
                        edit.putString("password", "");
                        edit.putBoolean("rememberPwd", false);
                        edit.apply();
                    }
                } else {
                    Toast.makeText(mContext, "用户名或密码不可为空 ", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_register:
                rl_registerPage.setVisibility(View.VISIBLE);
                rl_loginPage.setClickable(false);
                break;
            case R.id.btn_close1:
                rl_loginPage.setClickable(true);
                rl_registerPage.setVisibility(View.GONE);
                break;
            case R.id.btn_register1:
                String newUserName = String.valueOf(tv_new_account.getText()).trim();
                String newPassword = String.valueOf(tv_new_password.getText()).trim();
                RetrofitService retrofitService = retrofit.create(RetrofitService.class);
                if (!newUserName.equals("") && !newPassword.equals("")) {
                    Call<LoginBean> register = retrofitService.register(newUserName, newPassword);
                    register.enqueue(new Callback<LoginBean>() {
                        @Override
                        public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                            if (response.isSuccessful()) {
                                LoginBean body = response.body();
                                if (body.getStatus() != 0) {
                                    Message message = new Message();
                                    message.what = 1;
                                    ShowTipsHandler.sendMessage(message);
                                } else {
                                    Toast.makeText(mContext, "注册成功", Toast.LENGTH_SHORT).show();
                                    rl_registerPage.setVisibility(View.GONE);
                                    rl_loginPage.setClickable(true);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<LoginBean> call, Throwable t) {

                        }
                    });
                } else {
                    Toast.makeText(mContext, "用户名或密码不可为空 ", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_backLogin:
                if (Login_page.getVisibility() == View.VISIBLE) {
                    rl_isBackLogin.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_certain:
                rl_isBackLogin.setVisibility(View.GONE);
                edit.putString("token", "");
                edit.apply();
                GlobalVariable.token = "";
                unLogin_page.setVisibility(View.VISIBLE);
                Login_page.setVisibility(View.GONE);
                break;
            case R.id.btn_cancel:
                rl_isBackLogin.setVisibility(View.GONE);
                break;
            case R.id.btn_watch:
                if (GlobalVariable.token.equals(""))
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                else {
                    Toast.makeText(mContext, "观看记录暂未完成", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_read:
                if (GlobalVariable.token.equals(""))
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                else {
                    Toast.makeText(mContext, "阅读记录暂未完成", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_collect:
                if (GlobalVariable.token.equals(""))
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                else {
                    Toast.makeText(mContext, "壁纸收藏暂未完成", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onFocusChange(View v, boolean hasFocus) {

    }

    Handler ShowTipsHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                Toast.makeText(mContext, "用户名已经存在了", Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(mContext, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
    };
}
